package com.whut.cristiano.autographbook.Util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.whut.cristiano.autographbook.Model.HandlePictureListener;
import com.whut.cristiano.autographbook.Model.UploadPhotoBean;
import com.whut.cristiano.autographbook.MyApplication;

import java.io.File;
import java.io.FileOutputStream;

import de.hdodenhof.circleimageview.CircleImageView;


/**
 * Created by ykbboom on 2017/3/2 12:12
 * email：ykbpro@whut.edu.cn
 */

public class ImageUtil {
    private static final String TAG = "ImageUtil";
    public static final int TAKE_PIC = 1000;
    public static final int COMPLETE_CROP_CODE = 1001;
    public static final int SELECT_PIC_KITKAT = 1002;
    public static final int IMAGE_REQUEST_CODE = 1003;

    private String IMAGE_FILE_NAME = System.currentTimeMillis()+".jpg";

    private CircleImageView circleImageView;
    private ImageView imageView;
    private Context mContext;
    private Activity activity;
    private Fragment fragment;
    private static String realPath;//上传照片的路径


    public ImageUtil(CircleImageView imageView, Activity activity){
        this.circleImageView = imageView;
        this.activity = activity;
        mContext = MyApplication.getContext();
    }
    public ImageUtil(ImageView imageView, Activity activity){
        this.imageView = imageView;
        this.activity = activity;
        mContext = MyApplication.getContext();
    }

    public ImageUtil(ImageView imageView, Activity activity,Fragment fragment){
        this.imageView = imageView;
        this.activity = activity;
        this.fragment = fragment;
        mContext = MyApplication.getContext();
    }

    /**
     * 选择图片方式
     * */
    public void choosePhoto(){
        new AlertDialog.Builder(activity).
                setTitle("选择图片")
                .setMessage("请选择一种方式")
                .setPositiveButton("拍一张",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            openCamera();
                    }})
                .setNegativeButton("相册选一张", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            openAlbum();
                    }
                })
                .show();
    }
    /**
     * 打开相机
     * */
    public void openCamera(){
        Intent intentOpenCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentOpenCamera.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        activity.startActivityForResult(intentOpenCamera, TAKE_PIC);
        LogUtil.d(TAG,"打开相机");
    }
    /**
     * 打开相册
     */
    public void openAlbum(){

        Intent intentOpenAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        intentOpenAlbum.addCategory(Intent.CATEGORY_OPENABLE);
        intentOpenAlbum.setType("image/*");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            activity.startActivityForResult(intentOpenAlbum, SELECT_PIC_KITKAT);
            LogUtil.d(TAG,"打开相册");
        } else {
            activity.startActivityForResult(intentOpenAlbum, IMAGE_REQUEST_CODE);
        }
    }
    /**
     * 打开相册
     * 嵌套Fragment
     */

    public void openAlbumFragment(){

        Intent intentOpenAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        intentOpenAlbum.addCategory(Intent.CATEGORY_OPENABLE);
        intentOpenAlbum.setType("image/*");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            fragment.startActivityForResult(intentOpenAlbum, SELECT_PIC_KITKAT);
            LogUtil.d(TAG,"打开相册");
        } else {
            fragment.startActivityForResult(intentOpenAlbum, IMAGE_REQUEST_CODE);
        }
    }

    /**
     * 将拍摄的照片进行裁剪
     * */
    public void cropPic(){
            //照相机
            String sdCardStatus = Environment.getExternalStorageState();
            // 检测sd是否正常挂载
            if (!sdCardStatus.equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(mContext,"内存卡异常，请检查内存卡插入是否正确", Toast.LENGTH_SHORT).show();
                return;
            }
            File tempFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
            startPhotoZoom(Uri.fromFile(tempFile));

    }
    /**
     * 进行裁剪
     * Activity
     * */
    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.e("TAG", "The uri is not exist.");
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            String url = this.getPath(activity.getApplication(), uri);
            LogUtil.i(TAG,"裁剪图片Url:"+url);
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
        } else {
            intent.setDataAndType(uri, "image/*");
        }
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, COMPLETE_CROP_CODE);
    }

    /**
     * 图库的照片选择过后加载到ImageView
     * 适用于Activity
     */
    public void bitmapFactory(Uri uri){
        LogUtil.i(TAG,"uri:"+uri.toString());

        realPath= getPath(mContext,uri);
        LogUtil.i(TAG,realPath);
        if(!TextUtils.isEmpty(realPath)){
//            realPath="file:///"+realPath;
//            ImageLoader.getInstance().displayImage(filepath,imageView);
            //缓存临时头像的路径
            SharedPrefUtil.saveUserPhotoTempPath(realPath);
            Glide.with(mContext).load(uri).centerCrop().into(circleImageView);
        }
    }
    /**
     * 图库的照片选择过后加载到ImageView
     * 适用于嵌套Fragment
     */
    public void bitmapFactoryFragment(Uri uri){
        LogUtil.i(TAG,"uri:"+uri.toString());

        realPath= getPath(mContext,uri);
        LogUtil.i(TAG,realPath);
        if(!TextUtils.isEmpty(realPath)){
//            realPath="file:///"+realPath;
//            ImageLoader.getInstance().displayImage(filepath,imageView);
            //缓存纪念卡图片路径
            SharedPrefUtil.saveTemplateOnePicUrl(realPath);
            Glide.with(mContext).load(uri).fitCenter().into(imageView);
        }
    }
    /**
     * 拍一张显示图片
     * Activity
     * */
     public void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            realPath=saveBitmap(photo);
            LogUtil.i(TAG,"saveBitmap路径:"+realPath);
            //缓存临时头像的路径
            SharedPrefUtil.saveUserPhotoTempPath(realPath);
            Glide.with(mContext).load(realPath).fitCenter().into(circleImageView);
        }else{
            return;
        }
    }
    /**
     * 拍一张显示图片
     * Fragment
     * */
    public void setImageToViewFragment(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            realPath=saveBitmap(photo);
            LogUtil.i(TAG,"saveBitmap路径:"+realPath);

            SharedPrefUtil.saveTemplateOnePicUrl(realPath);
            Glide.with(mContext).load(realPath).fitCenter().into(imageView);
        }else{
            return;
        }
    }
    /**
     * 创建保存图片的文件夹
     */
    public void createDirectory(){
        String path= Environment.getExternalStorageDirectory()+"/autographbook/";
        File f=new File(path);
        if(!f.exists()){
            f.mkdir();
        }
    }

    /**
     * 保存图片,路径为 手机内存/autographbook/
     */
    public String saveBitmap(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Toast.makeText(mContext,"内存卡异常，请检查内存卡插入是否正确", Toast.LENGTH_SHORT).show();
            return "";
        }
//        String imageName=System.currentTimeMillis()+".jpg";
        File f = new File(Environment.getExternalStorageDirectory()+"/autographbook/",IMAGE_FILE_NAME);
        createDirectory();
        try {
            FileOutputStream outputStream= new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            LogUtil.i(TAG,f.getAbsolutePath());
            return f.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void templateSavePhoto(Bitmap mBitmap,HandlePictureListener listener) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Toast.makeText(mContext,"内存卡异常，请检查内存卡插入是否正确", Toast.LENGTH_SHORT).show();
        }
//        String imageName=System.currentTimeMillis()+".jpg";
        File f = new File(Environment.getExternalStorageDirectory()+"/autographbook/",IMAGE_FILE_NAME);
        createDirectory();
        try {
            FileOutputStream outputStream= new FileOutputStream(f);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            LogUtil.i(TAG,f.getAbsolutePath());
            listener.onStop(f.getAbsolutePath(),true,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 上传图片
     * */
    public void uploadPhoto(ProgressDialog progressDialog, HandlePictureListener handlePictureListener){
        UploadPhotoBean photoBean = new UploadPhotoBean(IMAGE_FILE_NAME,realPath);
        new OSSUtil(progressDialog, handlePictureListener).execute(photoBean);
    }

    public static void TemplateUploadPhoto(ProgressDialog progressDialog, HandlePictureListener handlePictureListener,String path){
        UploadPhotoBean photoBean = new UploadPhotoBean(System.currentTimeMillis()+".jpg",path);
        new OSSUtil(progressDialog, handlePictureListener).execute(photoBean);
    }
    /**
     * 得到根Fragment
     *
     * @return
     */
    private Fragment getRootFragment(Fragment frag) {
        Fragment fragment = frag.getParentFragment();
        while (fragment.getParentFragment() != null) {
            fragment = fragment.getParentFragment();
        }
        return fragment;

    }


    //Ps:原本uri返回的是file:///...，android4.4返回的是content://,所以这里要注意一下
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;

                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
